<template>
  <view>
    <u-popup v-model="showPayment" mode="bottom" :mask-close-able="false">
      <view class="pay-method">
        <view class="pay-method-title">
          <view class="pay-method-text">请选择支付方式</view>
          <view class="pay-method-close" @click="closePopup">
            <u-icon name="close" color="#999" size="32rpx"></u-icon>
          </view>
        </view>
        <view class="pay-method-list">
          <radio-group @change="radioChange">
            <label
              class="pay-method-item"
              v-for="(item, index) in paymentMethod"
              :key="item.value"
            >
              <view>{{ item.payDescribe }}</view>
              <view>
                <radio
                  :value="item.payType"
                  :checked="item.payType === currentPay"
                />
              </view>
            </label>
          </radio-group>
        </view>
        <view class="pay-method-btn">
          <button
            class="u-reset-button co-primary-button"
            hover-class="co-primary-button--hover"
            :loading="!showPayment"
            @click="confirmHandle"
          >
            确定
          </button>
        </view>
      </view>
    </u-popup>
    <pay-panel
      ref="payPanelRef"
      @payFail="payFailCb"
      @paySuccess="paySuccessCb"
      :scene="payScene"
    ></pay-panel>
  </view>
</template>

<script>
import { apiGetPayMethods, apiWeixinPayment, apiGetOpenId } from '@/api/order'
export default {
  props: {
    /**
     * 支付场景
     * cart 购物车下单支付场景
     * goods 商品下单支付场景
     * order 订单列、详情支付场景
     * */
    scene: {
      type: String,
      default: () => 'cart'
    }
  },
  data() {
    return {
      paymentMethod: [],
      currentPay: '',
      showPayment: false,
      orderIdArr: []
    }
  },
  methods: {
    pay_out(orderIdArr) {
      this.orderIdArr = orderIdArr
      this.showPayment = true
      this.getPaymentMethods()
    },
    // 获取支付方式
    getPaymentMethods() {
      apiGetPayMethods(this.orderIdArr)
        .then((res) => {
          console.log(res)
          let { code, data, msg } = res.data
          if (code == 200) {
            this.paymentMethod = data
          } else {
            this.$am_toast.warning(msg)
            this.showPayment = false
            this.$emit('payFail', {
              type: 'pay_error',
              orderIds: this.orderIdArr
            })
          }
        })
        .catch((err) => {
          console.log(err)
          this.$am_toast.error('获取支付方式错误，请重试')
          this.showPayment = false
        })
    },
    // 选择支付方式
    radioChange(value) {
      this.currentPay = value.detail.value
    },
    confirmHandle() {
      this.showPayment = false
      if (this.currentPay !== 'weChat') {
        let orderInfo = this.paymentMethod.filter(
          (item) => item.payType == this.currentPay
        )
        this.$refs.payPanelRef.pay_out(this.orderIdArr, orderInfo)
      } else {
        if (this.$store.getters.getOpenId) {
          this.weixinPay()
        } else {
          this.getWeixinInfo()
        }
      }
    },
    // 获取微信用户信息
    getWxUserProfile() {
      if (uni.getUserProfile) {
        uni.getUserProfile({
          desc: '获取您的信息将用来创建订单',
          lang: 'zh_CN',
          success: function (res) {
            console.log(res)
          },
          fail: function (err) {
            console.log(err)
          },
          complete: () => {
            this.getWeixinInfo()
          }
        })
      } else {
        this.getWeixinInfo()
      }
    },
    // 获取微信用户openId
    getWeixinInfo() {
      let _this = this
      uni.showLoading({
        mask: true,
        title: '加载中'
      })
      uni.login({
        provider: 'weixin',
        onlyAuthorize: true,
        success: function (loginRes) {
          console.log(JSON.stringify(loginRes))
          apiGetOpenId({ code: loginRes.code })
            .then((res) => {
              console.log(res)
              let { code, data, msg } = res.data
              if (code == 200) {
                // 获取成功
                _this.$store.commit('SET_OPEN_ID', data.openid)
                _this.weixinPay()
              } else {
                _this.$am_toast.warning(msg)
              }
            })
            .catch((err) => {
              console.log(err)
              uni.hideLoading()
              _this.$am_toast.warning('支付失败！')
              this.$emit('payFail', {
                type: 'pay_error',
                orderIds: this.orderIdArr
              })
            })
        },
        fail: function (err) {
          uni.hideLoading()
          _this.$am_toast.warning('支付失败！')
          this.$emit('payFail', {
            type: 'pay_error',
            orderIds: this.orderIdArr
          })
        }
      })
    },
    // 微信支付
    weixinPay() {
      uni.showLoading({
        mask: true,
        title: '加载中'
      })
      uni.getProvider({
        service: 'payment',
        success: (reson) => {
          apiWeixinPayment({ oid: this.orderIdArr[0] })
            .then((res) => {
              console.log(res, 'resres')
              let { code, data, msg } = res.data
              uni.hideLoading()
              if (code == 200) {
                uni.requestPayment({
                  provider: reson.provider[0],
                  timeStamp: data.timeStamp,
                  nonceStr: data.nonceStr,
                  package: data.package,
                  signType: data.signType,
                  paySign: data.paySign,
                  success: (payRes) => {
                    console.log(payRes)
                    this.$emit('paySuccess')
                  },
                  fail: (payErr) => {
                    console.log(
                      payErr,
                      'payErrpayErrpayErrpayErrpayErrpayErrpayErrpayErr'
                    )
                    this.$am_toast.warning('支付失败！')
                    this.$emit('payFail', {
                      type: 'pay_error',
                      orderIds: this.orderIdArr
                    })
                  }
                })
              } else {
                this.$am_toast.warning(msg)
                this.$emit('payFail', {
                  type: 'pay_error',
                  orderIds: this.orderIdArr
                })
              }
            })
            .catch((err) => {
              console.log(err, 'errerrerrerrerrerr')
              uni.hideLoading()
              this.$am_toast.warning('支付失败！支付失败！')
              this.$emit('payFail', {
                type: 'pay_error',
                orderIds: this.orderIdArr,
                scene: this.scene
              })
              this.showPayment = true
            })
        }
      })
    },
    closePopup() {
      uni.showModal({
        title: '放弃付款',
        content: '是否放弃本次付款？',
        confirmColor: '#4BB019',
        success: (cancelRes) => {
          if (cancelRes.confirm) {
            this.showPayment = false
            this.$emit('payFail', {
              type: 'user_cancel',
              orderIds: this.orderIdArr
            })
          }
        }
      })
    },
    payFailCb(data) {
      this.$emit('payFail', data)
    },
    paySuccessCb() {
      this.$emit('paySuccess')
    }
  }
}
</script>

<style lang="scss" scoped>
.pay-method {
  padding: 0 45rpx;
  position: relative;
  z-index: 999999;
}
.pay-method-title {
  position: relative;
  font-weight: bold;
  font-size: 34rpx;
  color: #fa3534;
  text-align: center;
}
.pay-method-text {
  padding: 25rpx 0;
  color: #333;
}
.pay-method-close {
  position: absolute;
  top: 30rpx;
  right: 0;
  z-index: 99;
}
.pay-method-list {
  height: 470rpx;
}
.pay-method-item {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
  &:last-child {
    border-bottom: 0;
  }
}
.pay-method-btn {
  margin-bottom: 40rpx;
}
</style>
